<template>
  <div class="app">
    <div v-if="shopId != ''">
      <div class="cashier_header_box">
        <div class="cashier_header_choose">
          <span class="cashier_header_choose_title">收银员：</span>
          <span class="cashier_header_choose_title">{{name}}</span>
        </div>
        <div class="cashier_header_choose">
          <span class="cashier_header_choose_title">门店：</span>
          <span class="cashier_header_choose_title">{{shopName}}</span>
        </div>
        <div class="cashier_header_choose">
          <span class="cashier_header_choose_title">日期：</span>
          <span class="cashier_header_choose_title">{{nowDate}}</span>
        </div>
      </div>
      <div class="cashier_content">
        <div class="cashier_content_item" style="flex-grow: 1">
          <shoppingCart ref="shopping" :tableData="productList" :memberForm='memberForm' :amount='amount'
            @tableIndexClick="tableIndexClick" @delClick="delClick" :key="timer" :memoTitle='memoTitle' :subQuantity="subQuantity"
            :discount='discount' :promotions='promotions'></shoppingCart>
        </div>
        <div class="cashier_content_item">
          <productHeader ref="product" :tableData="productList" @productClick="productClick" @clearClick="clearClick"
            @memberClick="memberClick" @tableIndexTwoClick='tableIndexTwoClick' @quantityClick="quantityClick"
            @priceClick="priceClick" @delClick="delClick" @depositClick="depositClick" @takeClick="takeClick"
            @memoClick='memoClick' @settlementClick="settlementClick" @smallTicketClick='smallTicketClick'></productHeader>
        </div>
      </div>
    </div>
    <div v-if="shopId == ''">
      <el-dialog title="请选择门店" :show-close='false' :close-on-click-modal='false' :close-on-press-escape="false"
        :visible.sync="dialogVisible" width="30%">
        <el-select style="width: 100%;" filterable value-key="id" clearable :filter-method="loadShopClick" v-model="shopIds"
          filterable placeholder="请选择" @change="loadShop">
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item">
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="closeSelectedTag">取 消</el-button>
          <el-button type="primary" @click="shopClick">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <el-dialog title="取单" :visible.sync="takeType" width="650px" :before-close="takeClose">
      <el-table :data="takeForm" style="width: 100%" height="300px">
        <el-table-column prop="startDate" label="挂单时间" width="220">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.startDate }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="itemList[0].name" label="商品名" width="220">
          <template slot-scope="scope">
            <div style="display: flex;flex-direction: column">
              <span class="shopping_product_title">{{ scope.row.itemList[0].name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="memberForm.name" label="会员名" width="100">
        </el-table-column>
        <el-table-column label="操作" width="50">
          <template slot-scope="scope">
            <el-button @click.native.prevent="takeIndexRow(scope.$index)" type="text" size="small">
              取单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="takeType = false">取 消</el-button>
      </span>
    </el-dialog>
    <tickPrint ref='tickPrint' style="opacity: 0;display: none;" :printForm="printForm"></tickPrint>
  </div>
</template>

<script>
  import shoppingCart from '@/views/cashier/components/shoppingCart'
  import productHeader from '@/views/cashier/components/productHeader'
  import tickPrint from '@/components/TickPrint/index'
  import {
    mapGetters
  } from 'vuex'
  import {
    calculate,
    save
  } from '@/api/order'
  import {
    list as shopList
  } from '@/api/shop'
  export default {
    data() {
      return {
        options: [],
        value: '',
        printForm:{},
        productList: [],
        memberId: '',
        memberForm: null,
        form: {
          memberId: '',
          operatorId: ''
        },
        amount: 0,
        nowDate: "", // 当前日期
        nowTime: "", // 当前时间
        nowWeek: "", // 当前星期
        shopName: '',
        shopId: '',
        dialogVisible: true,
        query: {
          name: ''
        },
        shopIds: '',
        tableIndex: 0,
        timer: null,
        takeType: false,
        takeForm: [],
        memoTitle: '请输入备注',
        subQuantity: 0,
        discount: 0,
        promotions: [],
        formData:null
      }
    },
    components: {
      shoppingCart,
      productHeader,
      tickPrint
    },
    computed: {
      ...mapGetters([
        'employee', 'name'
      ])
    },
    mounted() {
      // 页面加载完后显示当前时间
      this.dealWithTime(new Date())
      // 定时刷新时间
      this.timer = setInterval(() => {
        this.dealWithTime(new Date()) // 修改数据date
      }, 500)
    },
    destroyed() {
      if (this.timer) { // 注意在vue实例销毁前，清除我们的定时器
        clearInterval(this.timer);
      }
    },
    created() {
      this.getList()
    },
    methods: {
      productClick(data) {
        var _this = this
        data.quantity = 1
        data.amount = 0
        _this.productList.push(data)
        _this.procuctFilter()
        _this.calculateClick()
        this.timer = new Date().getTime()
      },
      //商品过滤
      procuctFilter() {
        let newfood = [];
        var temp = {};
        for (var i in this.productList) {
          var key = this.productList[i].id;
          if (temp[key]) {
            temp[key].id = temp[key].id;
            temp[key].quantity = temp[key].quantity + this.productList[i].quantity;
            temp[key].amount = parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity);
          } else {
            temp[key] = {};
            temp[key].id = this.productList[i].id;
            temp[key].quantity = this.productList[i].quantity;
            temp[key].amount = parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity);
          }
          temp[key].subType = this.productList[i].subType;
          temp[key].name = this.productList[i].name;
          temp[key].sn = this.productList[i].sn;
          temp[key].price = this.productList[i].price;
          temp[key].cost = this.productList[i].cost;
          temp[key].orders = this.productList[i].orders;
          temp[key].discount = this.productList[i].discount;
          temp[key].spec = this.productList[i].spec;
          temp[key].unit = this.productList[i].unit
          temp[key].stock = this.productList[i].stock
        }
        for (var k in temp) {
          newfood.push(temp[k])
        }
        this.productList = newfood
      },
      //  计算
      calculateClick() {
        var _this = this;
        let itemList = [];
        console.log(_this.productList)
        _this.productList.forEach(function(item) {
          if (item.productId != '') {
            var goodsDetails = {
              productId: item.id,
              name: item.name,
              sn: item.sn,
              price: item.price,
              subType: item.subType,
              quantity: item.quantity,
              spec: item.spec,
              cost: item.cost,
              availableReturnQuantity: 0,
              availableShippedQuantity: 0
            };
            itemList.push(goodsDetails)
          }
        });
        let formData = {
          memberId: _this.form.memberId,
          itemList: itemList,
          operatorId: _this.employee,
          memo: _this.memoTitle
        }
        calculate(formData).then(response => {
          this.amount = response.data.amount
          this.subQuantity = response.data.order.subQuantity
          this.discount = response.data.order.discount
          this.promotions = response.data.order.promotions
          this.formData = response.data.order
        }).catch(error => {

        })
      },
      clearClick() {
        this.productList = []
        this.amount = 0
        this.memberForm = null
        this.form.memberId = ''
        this.memoTitle = ''
        this.subQuantity = 0
        this.discount = 0
        this.promotions = []
        this.$refs.product.clearClickTwo()
      },
      memberClick(data) {
        this.memberForm = data
        this.form.memberId = data.id
      },
      dealWithTime(data) { // 获取当前时间
        let formatDateTime;
        let Y = data.getFullYear();
        let M = data.getMonth() + 1;
        let D = data.getDate();
        let H = data.getHours();
        let Min = data.getMinutes();
        let S = data.getSeconds();
        let W = data.getDay();
        H = H < 10 ? "0" + H : H;
        Min = Min < 10 ? "0" + Min : Min;
        S = S < 10 ? "0" + S : S;
        switch (W) {
          case 0:
            W = "日";
            break;
          case 1:
            W = "一";
            break;
          case 2:
            W = "二";
            break;
          case 3:
            W = "三";
            break;
          case 4:
            W = "四";
            break;
          case 5:
            W = "五";
            break;
          case 6:
            W = "六";
            break;
          default:
            break;
        }
        this.nowDate = Y + "年" + M + "月" + D + "日 " + H + ":" + Min + ":" + S;
        this.nowWeek = "周" + W;
        this.nowTime = H + ":" + Min + ":" + S;
        // formatDateTime = Y + "年" + M + "月" + D + "日 " + " 周" +W + H + ":" + Min + ":" + S;
      },
      getList() {
        var _this = this
        const params = new URLSearchParams()
        params.append('name', this.query.name)
        params.append('type', 0)
        shopList(params)
          .then(resolve => {
            console.log(resolve)
            if (resolve.data.data.length == 1) {
              _this.shopName = resolve.data.data[0].name
              _this.shopId = resolve.data.data[0].id
            } else {
              _this.options = resolve.data.data
            }
          })
          .catch(error => {})
      },
      loadShopClick(query) {
        console.log(query)
        console.log('111')
        this.query.name = query
        this.getList()
      },
      shopClick() {
        console.log(this.shopIds.id)
        if (this.shopIds.id != undefined) {
          this.shopId = this.shopIds.id
        } else {
          this.$message('请选择门店')
        }
      },
      loadShop(data) {
        console.log(data)
        this.shopName = data.name
      },
      closeSelectedTag() {
        var view = {
          'path': "/cashier/index",
        }
        this.$store.dispatch('tagsView/delView', view).then(({
          visitedViews
        }) => {
          console.log(visitedViews)
          this.toLastView(visitedViews)
        })
      },
      toLastView(visitedViews) {
        const latestView = visitedViews.slice(-1)[0]
        console.log(latestView)
        this.$router.push(latestView.fullPath)
      },
      tableIndexClick(data) {
        this.tableIndex = data
        this.$refs.product.tableIndexClick(this.tableIndex)
      },
      tableIndexTwoClick(data) {
        this.tableIndex = data
        this.$refs.shopping.tableIndexTwoClick(this.tableIndex)
      },
      quantityClick(data) {
        console.log(data)
        var _this = this
        if (data.quantity > 0) {
          _this.productList[data.tableIndex].quantity = data.quantity
          _this.productList[data.tableIndex].amount = parseFloat(data.quantity) * parseFloat(_this.productList[data.tableIndex]
            .price)
          _this.calculateClick()
        } else {
          this.$message({
            message: '数量不能等于0',
            type: 'success'
          });
        }
      },
      priceClick(data) {
        var _this = this
        console.log('1111')
        console.log(_this.productList[data.tableIndex].price)
        _this.productList[data.tableIndex].price = data.price
        _this.productList[data.tableIndex].amount = parseFloat(data.price) * parseFloat(_this.productList[data.tableIndex]
          .quantity)
        _this.calculateClick()
        // this.timer = new Date().getTime()
      },
      delClick(index) {
        var _this = this
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
          loading.close();
        }, 500);
        var indexData = 0
        console.log('删除商品')
        this.productList.splice(index, 1)
        if (this.productList.length != 0) {
          console.log('删除商品1')
          _this.calculateClick()
          // this.timer = new Date().getTime()
          this.$refs.product.tableIndexClick(indexData)
          this.$refs.shopping.tableIndexTwoClick(indexData)
        } else {
          console.log('删除商品2')
          this.productList = []
          this.amount = 0
          this.subQuantity = 0
          this.discount = 0
          this.promotions = []
          this.$refs.product.clearClickTwo()
          this.timer = new Date().getTime()
        }
      },
      depositClick() {
        var _this = this
        console.log('1111')
        console.log(JSON.parse(localStorage.getItem('deposit')))
        // localStorage.removeItem('deposit');
        if (_this.productList.length > 0) {
          var form = []
          if (JSON.parse(localStorage.getItem('deposit')) != null) {
            form = JSON.parse(localStorage.getItem('deposit'))
          }
          var data = {
            itemList: _this.productList,
            memberId: _this.form.memberId,
            memberForm: _this.memberForm,
            startDate: _this.nowDate,
          }
          form.push(data)
          localStorage.setItem('deposit', JSON.stringify(form));
          _this.$message('挂单成功')
          _this.clearClick()
        } else {
          alert('请选择商品')
        }
      },
      takeClick() {
        this.takeForm = []
        if (JSON.parse(localStorage.getItem('deposit')) != null) {
          this.takeForm = JSON.parse(localStorage.getItem('deposit'))
          this.takeType = true
        } else {
          alert('暂无挂单')
        }
      },
      takeClose() {
        this.takeType = false
      },
      takeIndexRow(index) {
        var _this = this
        this.$confirm('是否确认取单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.productList = _this.takeForm[index].itemList
          _this.form.memberId = _this.takeForm[index].memberId
          _this.memberForm = _this.takeForm[index].memberForm
          _this.calculateClick()
          _this.takeForm.splice(index, 1)
          console.log(_this.takeForm)
          localStorage.setItem('deposit', JSON.stringify(_this.takeForm));
          _this.$message('取单成功')
          _this.takeClose()
        }).catch(() => {

        });
      },
      memoClick(data) {
        this.memoTitle = data
        if (this.productList.length > 0) {
          this.calculateClick()
        }
      },
      settlementClick() {
        var _this = this
        if(this.productList.length > 0){
          this.$confirm('是否确认结账, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            _this.$delete(this.formData,'promotions')
            save(_this.formData).then(res => {
              loading.close();
              this.printForm=res.data
              console.log(this.printForm)
              _this.$message('结算成功');
              _this.clearClick()
            }).catch(error => {
              loading.close();
            })
          }).catch(() => {
            loading.close();
          });
        }else{
          this.$message('商品不能为空');
        }
      },
      smallTicketClick(){
        this.$refs.tickPrint.printPdf()
      }
    }
  }
</script>

<style scoped>
  .cashier_header_box {
    width: 100%;
    height: 6vh;
    border-bottom: 1px solid #F2F6FC;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .cashier_header_choose {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-left: 10px;
  }

  .cashier_header_choose_title {
    font-size: 1vw;
    color: #909399;
  }

  .cashier_content {
    display: flex;
    flex-direction: row;
  }

  .cashier_content_item {
    height: calc(94vh - 85px);
    position: relative;
  }

  /deep/.el-table__fixed-right::before {
    background-color: white !important;
  }

  /deep/.el-table td {
    border-bottom: 1px solid white !important;
  }

  /deep/.el-table--border th {
    background-color: rgba(241, 242, 243, 1) !important;
  }

  .shopping_product_title {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
